<template>
    <el-dialog v-model="visible" title="编辑价格区间" :close-on-click-modal="false" style="width: 30%;top:12%;"
        :close-on-press-escape="false">
        <el-form :model="dataForm" :rules="priceRules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="40px">
            <!-- 万以下价格区间 -->
            <el-form-item prop="priceUnder">
                    <el-input type="number" v-model.number="dataForm.priceUnder" placeholder="请输入价格" style="width: 300px;margin-right: 10px;"></el-input>
                    <el-text>万以下</el-text>
            </el-form-item>
            <!-- 区间价格 -->
            <el-form-item>
                <div v-for="(item, index) in rangeModels" :key="index" class="model-item">
                    <el-input v-model.number="item.startPrice" placeholder="请输入" type="number"
                        style="width: 130px;margin-right: 10px;"></el-input>
                    <span style="margin-top: -10px;margin-left: -4px;">___</span>
                    <el-input v-model.number="item.endPrice" placeholder="请输入" type="number"
                        style="width: 130px;margin-left: 10px;"></el-input>
                    <el-text>万</el-text>
                    <img src="../../assets/images/add.jpg" alt="" @click="addRangeModel" class="addmodel">
                    <img v-if="rangeModels.length > 1" src="../../assets/images/delete2.jpg" alt=""
                        @click="removeRangeModel(index)">
                </div>
            </el-form-item>

            <!-- 万以上价格 -->
            <el-form-item prop="priceAbove">
                <el-input type="number" v-model.number="dataForm.priceAbove" placeholder="请输入" style="width: 300px;"></el-input>
                <el-text>万以上</el-text>
            </el-form-item>
        </el-form>
        <template v-slot:footer>
            <el-button @click="visible = false" class="quxiao">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getToken } from "@/utils/cache";
import app from "@/constants/app";
import { IObject } from "@/types/interface";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref<FormInstance | null>(null);
const dataForm = reactive({
    priceUnder: "", // 万以下
    priceAbove: "", // 万以上
});

// 分开存储不同类型的价格区间数据
const rangeModels = ref([{ startPrice: '', endPrice: '' }]); // 区间价格

// 校验万以下价格
const validatePriceUnder = (rule: any, value: string | number, callback: any) => {
    if (!value && value !== 0) {
        callback();
        return;
    }
    
    const price = Number(value);
    
    if (isNaN(price)) {
        callback(new Error('请输入有效的数字'));
        return;
    }
    
    // 检查是否小于等于所有区间的最低价
    const minRangePrice = Math.min(...rangeModels.value.map(item => Number(item.startPrice || Infinity)));
    
    if (!isNaN(minRangePrice) && price > minRangePrice) {
        callback(new Error('万以下价格必须小于等于所有区间的最低价'));
        return;
    }
    
    callback();
};

// 校验万以上价格
const validatePriceAbove = (rule: any, value: string | number, callback: any) => {
    if (!value && value !== 0) {
        callback();
        return;
    }
    
    const price = Number(value);
    
    if (isNaN(price)) {
        callback(new Error('请输入有效的数字'));
        return;
    }
    
    // 检查是否大于等于所有区间的最高价
    const maxRangePrice = Math.max(...rangeModels.value.map(item => Number(item.endPrice || -Infinity)));
    
    if (!isNaN(maxRangePrice) && price < maxRangePrice) {
        callback(new Error('万以上价格必须大于等于所有区间的最高价'));
        return;
    }
    
    callback();
};

// 价格校验规则
const priceRules = reactive<FormRules>({
    priceUnder: [
        { required: true, message: '请输入万以下价格', trigger: 'blur' },
        { validator: validatePriceUnder, trigger: 'blur' }
    ],
    priceAbove: [
        { required: true, message: '请输入万以上价格', trigger: 'blur' },
        { validator: validatePriceAbove, trigger: 'blur' }
    ]
});

// 添加区间价格输入框
const addRangeModel = () => {
    rangeModels.value.push({ startPrice: '', endPrice: '' });
};

// 删除区间价格输入框
const removeRangeModel = (index: number) => {
    if (rangeModels.value.length <= 1) {
        ElMessage.warning('至少需要一个价格区间');
        return;
    }
    rangeModels.value.splice(index, 1);
};

// 校验所有价格区间
const validateAllPrices = () => {
    let isValid = true;
    let errorMessage = '';
    
    // 校验每个区间
    rangeModels.value.forEach((item, index) => {
        const startPrice = Number(item.startPrice);
        const endPrice = Number(item.endPrice);
        
        // 校验区间内部顺序
        if (!isNaN(startPrice) && !isNaN(endPrice) && startPrice >= endPrice) {
            isValid = false;
            errorMessage = `第${index + 1}个区间的起始价格必须小于结束价格`;
            return false;
        }
        
        // 校验区间与上下价格的关系
        const priceUnder = Number(dataForm.priceUnder);
        const priceAbove = Number(dataForm.priceAbove);
        
        if (!isNaN(priceUnder) && !isNaN(startPrice) && startPrice < priceUnder) {
            isValid = false;
            errorMessage = `第${index + 1}个区间的起始价格必须大于等于万以下价格`;
            return false;
        }
        
        if (!isNaN(priceAbove) && !isNaN(endPrice) && endPrice > priceAbove) {
            isValid = false;
            errorMessage = `第${index + 1}个区间的结束价格必须小于等于万以上价格`;
            return false;
        }
    });
    
    if (!isValid) {
        ElMessage.warning(errorMessage);
        return false;
    }
    
    return true;
};

// 初始化方法
const init = (id?: number | undefined) => {
    visible.value = true;

    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields();
    }

    // 重置模型数据
    rangeModels.value = [{ startPrice: '', endPrice: '' }];
    dataForm.priceUnder = '';
    dataForm.priceAbove = '';

    // 获取现有价格配置数据
    baseService.get('/noc/priceconfig/list')
        .then((res) => {
            if (res && res.code === 0 && res.data) {
                // 处理返回的数据
                const priceConfigList = res.data;

                // 遍历配置数据并填充到表单
                priceConfigList.forEach((item: any) => {
                    if (item.type === 1) {
                        // 万以下价格
                        dataForm.priceUnder = item.price;
                    } else if (item.type === 2) {
                        // 区间价格
                        const [startPrice, endPrice] = item.price.split(',');

                        // 如果是第一个区间价格，更新已有的空对象
                        if (item.sort === 0) {
                            rangeModels.value[0].startPrice = startPrice;
                            rangeModels.value[0].endPrice = endPrice;
                        } else {
                            // 否则添加新的区间
                            rangeModels.value.push({
                                startPrice,
                                endPrice
                            });
                        }
                    } else if (item.type === 3) {
                        // 万以上价格
                        dataForm.priceAbove = item.price;
                    }
                });
            }
        })
        .catch((error) => {
            console.error('获取价格配置失败:', error);
            ElMessage.error('获取价格配置失败');
        });
};

// 表单提交
const dataFormSubmitHandle = () => {
    if (!dataFormRef.value) return;
    
    dataFormRef.value.validate((valid) => {
        if (valid) {
            // 校验所有价格区间
            if (!validateAllPrices()) {
                return;
            }
            
            // 构造符合接口要求的数据格式
            const requestData = [];

            // 处理万以下价格区间 (type: 1)
            if (dataForm.priceUnder) {
                requestData.push({
                    "type": 1,
                    "price": dataForm.priceUnder
                });
            }

            // 处理区间价格 (type: 2)
            rangeModels.value.forEach((item, index) => {
                if (item.startPrice && item.endPrice) {
                    requestData.push({
                        "type": 2,
                        "price": `${item.startPrice},${item.endPrice}`,
                        "sort": index
                    });
                }
            });

            // 处理万以上价格 (type: 3)
            if (dataForm.priceAbove) {
                requestData.push({
                    "type": 3,
                    "price": dataForm.priceAbove
                });
            }

            console.log('提交接口数据:', requestData);

            // 调用保存接口
            if (requestData.length > 0) {
                baseService.post('/noc/priceconfig/save', requestData)
                    .then((res) => {
                        if (res && res.code === 0) {
                            ElMessage.success('保存成功');
                            visible.value = false;
                            emit('refreshDataList');
                        } else {
                            ElMessage.error(res?.msg || '保存失败');
                        }
                    })
                    .catch((error) => {
                        console.error('保存失败:', error);
                        ElMessage.error('保存失败');
                    });
            } else {
                ElMessage.warning('请至少填写一项价格区间');
            }
        } else {
            ElMessage.warning('请检查并修正价格区间设置');
            return false;
        }
    });
};

defineExpose({
    init
});
</script>

<style scoped lang="scss">
/* 样式部分保持不变 */
.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);
}

.uploaded-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
    transition: transform 0.2s;
}

.uploaded-image:hover {
    transform: scale(1.05);
}

.brand-upload {
    .upload-box {
        width: 100px;
        height: 100px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;

        &:hover {
            border-color: #409eff;
        }

        .icon {
            width: 60px;
            height: 60px;
        }
    }

    .el-upload__tip {
        font-size: 12px;
        color: #606266;
        margin-top: 7px;
    }
}

.el-text {
    color: #606266;
    margin-left: 30px;
}

.model-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

.model-select {
    padding: 8px;
    margin-right: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.model-input {
    padding: 8px;
    margin-right: 10px;
    border-radius: 5px;
    width: 218px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(199, 199, 199, 1);
}

.model-input:focus {
    border: 0px;
    /* 获得焦点时边框颜色改为蓝色 */
    background: rgba(240, 245, 255, 1);
    color: rgba(22, 119, 255, 1);
    outline: none;
    /* 去除默认的焦点轮廓 */
}

.remove-button {
    padding: 8px 12px;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
.addmodel{
    margin-left: 10px;
    margin-right: 20px;
}
</style>